package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    /**
     * 过滤器执行的逻辑
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求地址
        String path = request.getURI().getPath();
        // 判断请求地址是否需要鉴权
        if (path.contains("/login")) {
            // 不需要鉴权的地址,直接放行
            return chain.filter(exchange);
        }
        // 需要鉴权的地址,判断是否有token
        // 从请求头中获取token
        String token = request.getHeaders().getFirst("token");
        // 如果token不存在,提示401未授权
        // token存在,使用JWT解析token
        if (!StringUtils.isEmpty(token)) {
            // token有效,从token中解析出用户自定义的userId
            try {
                Claims claimsBody = AppJwtUtil.getClaimsBody(token);
                int result = AppJwtUtil.verifyToken(claimsBody);
                if (result == -1 || result == 0) {
                    // 将userId放入到请求头中,转发到下游的微服务
                    Object userId = claimsBody.get("userId");
                    Object name = claimsBody.get("name");
                    request.mutate().header("userId", userId.toString());
                    request.mutate().header("name", name.toString());
                    return chain.filter(exchange);
                }

            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        // token无效,提示401
        // 所有异常,直接提示401未授权
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    /**
     * 过滤器执行的顺序 数值越小,优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
